# This Python file uses the following encoding: utf-8

from django.db import models
from django.db.models import get_model
from django.contrib.auth.models import User, Group


class Departament(models.Model):
    id_departament = models.AutoField(primary_key=True)
    codi = models.CharField(max_length=4 )
    nom = models.CharField(max_length=300 )

    class Meta:
        ordering = ['nom', ]
        db_table = u'departaments'
        verbose_name = u"Departament Didàctic"
        verbose_name_plural = u"Departaments Didàctics"        

    def __unicode__(self):
        return unicode( self.nom )

class AlumneUserManager(models.Manager):
    def get_query_set(self):
        grupAlumnes = None
        try:
            grupAlumnes = Group.objects.get( name = 'alumne' )
        except:
            pass
        return super(AlumneUserManager, self).get_query_set().filter( groups = grupAlumnes   )


class AlumneUser(User):
    objects = AlumneUserManager()
    class Meta:
        proxy = True
        ordering = ['last_name','first_name','username']

    def getUser(self):
        return User.objects.get( pk = self.pk )

    def getAlumne(self):
        alumne = None
        try:
            alumne = self.alumne
        except:
            pass
        return alumne
                        
    def __unicode__(self):
        return unicode( self.getAlumne() )
     

#----------------------------------------------------------------------------------------------

class ProfessorManager(models.Manager):
    def get_query_set(self):
        grupProfessors = None
        try:
            grupProfessors = Group.objects.get( name = 'professors' )
        except:
            pass
        return super(ProfessorManager, self).get_query_set().filter( groups = grupProfessors   )


class Professor(User):
    objects = ProfessorManager()
    class Meta:
        proxy = True
        ordering = ['last_name','first_name','username']

    def getUser(self):
        return User.objects.get( pk = self.pk )
    
    def nMissatgesNoLlegits(self):
        self.destinatari_set.filter( moment_lectura__isnull = True ).count()
                    
    def __unicode__(self):
        str = self.first_name + u' ' + self.last_name if self.last_name else self.username 
        return str.title()  
     
def User2Professor( user ):
    professor = None
    try:
        professor = Professor.objects.get( pk = user.pk )
    except:
        pass
    return professor

#----------------------------------------------------------------------------------------------

class ProfessionalManager(models.Manager):
    def get_query_set(self):
        grupProfessional = None
        try:
            grupProfessional = Group.objects.get( name = 'professional' )
        except:
            pass
        return super(ProfessionalManager, self).get_query_set().filter( groups = grupProfessional   )

class Professional(User):
    objects = ProfessionalManager()
    class Meta:
        proxy = True
        ordering = ['last_name','first_name','username']

    def getUser(self):
        return User.objects.get( pk = self.pk )
                    
    def __unicode__(self):
        str = self.first_name + u' ' + self.last_name if self.last_name else self.username 
        return str.title() 

def User2Professional( user ):
    professional = None
    try:
        professional = Professional.objects.get( pk = user.pk )
    except:
        pass
    return professional

#----------------------------------------------------------------------------------------------

class Accio(models.Model):
    TIPUS_ACCIO_CHOICES = (
        ('PL','Passar llista'),
        ('LL','Posar o treure alumnes a la llista'),
        ('IN','Posar o treur Incidència'),
        ('EE','Editar Expulsió'),
        ('EC','Expulsar del Centre'),
        ('RE','Recullir expulsió'),
        ('AC','Registre Actuació'),
        ('AG','Actualitza alumnes des de Saga'),
        ('MT','Envia missatge a tutors' ),
        ('SK','Sincronitza Kronowin'),
        ('JF','Justificar Faltes'),        
        ('NF','Notificacio Families'),        
    )
    tipus = models.CharField(max_length=2, choices=TIPUS_ACCIO_CHOICES)
    usuari = models.ForeignKey( User, db_index = True, related_name = 'usuari' )
    impersonated_from = models.ForeignKey( User, blank = True, null = True, related_name = 'impersonate_from' )
    moment = models.DateTimeField( auto_now_add = True,  db_index = True )
    l4 = models.BooleanField( default = False )
    text = models.TextField( )
    class Meta:
        db_table = u'accio_usuari'
        verbose_name = u"Acció d'usuari"
        verbose_name_plural = u"Accions d'usuari"
    def __unicode__(self):
        txt_imp = u'({0})'.format(self.impersonated_from) if self.impersonated_from else ''
        return u'{0} {1} {2} {3} {4}'.format( self.moment, self.tipus, self.data, self.user, txt_imp )
    
#----------------------------------------------------------------------------------------------

class LoginUsuari(models.Model):   
    exitos = models.BooleanField()
    usuari = models.ForeignKey( User, db_index = True, related_name = 'LoginUsuari' )
    moment = models.DateTimeField( auto_now_add = True,  db_index = True )
    ip = models.CharField( max_length = 12, blank = True )
    class Meta:
        ordering = ['usuari', '-moment']
        db_table = u'login_usuari'
        verbose_name = u"Login d'usuari"
        verbose_name_plural = u"Login d'usuari"
    #cal crear index a mà: create index login_usuar_u_m_idx1 on login_usuari ( usuari_id , moment desc );

class OneTimePasswd(models.Model):
    usuari = models.ForeignKey( User, db_index = True)
    moment_expedicio = models.DateTimeField( auto_now_add = True )
    clau = models.CharField(max_length=40 )
    reintents = models.IntegerField( default = 0 )
